#!/usr/bin/env python

import datetime
import logging

from google.appengine.ext import db

import idigi
from config import Config 

USERNAME = Config.USERNAME
PASSWORD = Config.PASSWORD
DEVICE_ID = Config.DEVICE_ID

CHANNEL_LIST = (
    'xbr0.temperature',
    'xbr0.light',
    'xbib0.led1',
	'xbr1.temperature',
    'xbr1.light',
	'xbib0.led2',
	'sensor0.temperature',
    'sensor0.light',
    'xbib0.led3'
)

def update():
    idigi_client = idigi.iDigiClient(
        username=USERNAME, password=PASSWORD)
    new_samples = idigi_client.channel_dump(
        device_id=DEVICE_ID)
    new_samples = filter(lambda s: s.channel_name in CHANNEL_LIST, new_samples)
    for new_sample in new_samples:
        extant_sample_q = db.GqlQuery("SELECT * FROM Sample "
                                    "WHERE channel_name = :1 AND "
                                    "      timestamp = :2 "
                                    "LIMIT 1",
                                    new_sample.channel_name,
                                    new_sample.timestamp)
        extant_sample = extant_sample_q.get()
        if extant_sample:
            logging.debug("cron_idigi_pull: skipped update of %s" 
                                % new_sample.channel_name)
            continue
        # Occasionally we see timeouts from the Google data store,
        # let's make sure we retry this put() call on failure:
        retries = 3
        while 1:
            try:
                new_sample.put()
                break
            except Exception, e:
                logging.warning("cron_idigi_pull: exception while putting "
                                " to Google data store.")
                retries -= 1
                time.sleep(2.5)
                if not retries:
                    raise e
        logging.debug("cron_idigi_pull: updated %s" % new_sample.channel_name)

    
def purge():
    # only keep 24 hours of data in the data store:
    one_day_ago = (datetime.datetime.today() -
                   datetime.timedelta(days=1)) 
    old_sample_q = db.GqlQuery("SELECT * FROM Sample "
                      "WHERE timestamp < :1 "
                      "ORDER BY timestamp DESC ", one_day_ago)
    old_sample_count = old_sample_q.count(1000)
    if old_sample_count > 0:
        logging.debug("cron_idigi_pull: deleting %d samples"
                                % old_sample_count)
        old_samples = old_sample_q.fetch(400)  # 1000    
        db.delete(old_samples)
    else:
        logging.debug("cron_idigi_pull: no old samples to delete.")

def main():
    logging.getLogger().setLevel(logging.DEBUG)
    update()
    purge()
        
if __name__ == '__main__':
  main()
